package com.polaris.live.ui.main.fragment

import android.os.Bundle
import androidx.recyclerview.widget.RecyclerView
import androidx.viewbinding.ViewBinding
import com.polaris.live.common.mvvm.viewmodel.BaseViewModel
import com.polaris.live.manager.UserStateManager
import com.polaris.live.resp.back_resp.DisplayUserBean
import com.polaris.live.resp.back_resp.copyState
import com.polaris.live.utils.state.getDisplayIndices
import com.polaris.live.utils.state.getDisplayPosition
import com.polaris.live.widget.refresh.OnListListener

/**
 * AbstractHotManFragment
 *
 * @author Created by lucas on 2023/11/4 17:41
 */
abstract class AbstractHotManFragment<VM, VB> : AbstractHotListFragment<VM, VB>()
        where VB : ViewBinding, VM : BaseViewModel, VM : OnListListener {

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        UserStateManager.observe(this, {
            getDisplayUserIds()
        }, { messages ->
            val indices = refreshView.recycler.getDisplayIndices(mAdapter.data)

            messages.forEach { message ->
                for (i in indices) {
                    val item = mAdapter.getItem(i)
                    if (item is DisplayUserBean && item.base.userId == message.state.userId) {
                        mAdapter.setData(i, item.copyState(message))
                        break
                    }
                }
            }
        })
        refreshView.recycler.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    updateUserStateObserve()
                }
            }
        })
    }

    private fun updateUserStateObserve(userIds: List<Long> = getDisplayUserIds()) {
        UserStateManager.updateUserObserve(this, userIds)
    }

    private fun getDisplayUserIds(): List<Long> {
        val wrapper = refreshView.recycler.getDisplayPosition(mAdapter.data)
            ?: return emptyList()

        return mAdapter.data.subList(wrapper.firstPosition, wrapper.lastPosition).mapNotNull {
            if (it is DisplayUserBean) {
                it.base.userId
            } else {
                null
            }
        }
    }

}